package com.moore.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.moore.Servlet.UserServlet;
import com.moore.model.Admin;
import com.moore.model.User;

import javax.crypto.SecretKey;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;


public class UserUtils {

    public static User getUser(String acc, String pwd) {
        String password;
        try {
            SecretKey key = AESUtils.loadKey();
            password = AESUtils.encrypt(pwd, key);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String sql = "select * from users where account = '" + acc + "' and password = '" + password + "'";
        List<String> list;
        try {
            list = JDBCUtils.executeSelect(sql, "id","account", "password", "name", "avatar",
                    "balance", "Orders", "state", "insert_time", "update_time");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (list.isEmpty()) {
            getAdmin(acc,pwd);
        } else {
            String decryptedPassword;
            try {
                SecretKey key = AESUtils.loadKey();
                String originalPassword = list.get(2);
                decryptedPassword = AESUtils.decrypt(originalPassword, key);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            User user = new User(Integer.parseInt(list.get(0)), list.get(1),
                    decryptedPassword, list.get(3), list.get(4), Double.parseDouble(list.get(5)),
                    Integer.parseInt(list.get(6)), Integer.parseInt(list.get(7)), list.get(8),
                    list.get(9));
            UserServlet.getValue(user);
            return user;
        }
        return null;
    }

    public static String insertUser(User user) {
        String sql = "insert into users (id, account, password, name, avatar, balance, Orders, " +
                "state, insert_time, update_time) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        try {
            SecretKey key = AESUtils.loadKey();
            String encryptedPassword = AESUtils.encrypt(user.getPassword(), key);
            int num = JDBCUtils.executeUpdate(sql, user.getId(), user.getAccount(),
                    encryptedPassword, User.getName(), user.getAvatar(),
                    user.getBalance(), user.getOrders(), user.getState(),
                    user.getCreateTime(), user.getUpdateTime());
            if (num >= 1) {
                return "success";
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "fail";
    }

    public static List<String> getPassWord(String id){
        String sql = "select password from users where id = " + id;
        List<String> list;
        List<String> newList = new ArrayList<>();
        try {
            list = JDBCUtils.executeSelect(sql,"password");
            String decryptedPassword;
            try {
                SecretKey key = AESUtils.loadKey();
                decryptedPassword = AESUtils.decrypt(list.get(0), key);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            newList.add(decryptedPassword);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return newList;
    }

    public static Admin getAdmin(String acc, String pwd) {
        String sql = "select * from admins where account = '" + acc + "' and password = '" + pwd + "'";
        List<String> list;
        try {
            list = JDBCUtils.executeSelect(sql, "id","account", "password", "name", "avatar");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!list.isEmpty()) {
            Admin admin = new Admin(Integer.parseInt(list.get(0)), list.get(1), list.get(2), list.get(3), list.get(4));
            UserServlet.getValue(admin);
            return admin;
        }
        return null;
    }

    public static String update(String key1, String value, String id){
        String sql = "update users set " + key1 + " = ? ,update_time = ? where id = ?";
        int num;
        try {
            if (key1.equals("password")) {
                SecretKey key = AESUtils.loadKey();
                value = AESUtils.encrypt(value, key);
            }
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String time = now.format(formatter);
            num = JDBCUtils.executeUpdate(sql,value,time,id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (num >= 1){
            return "success";
        }
        return "fail";
    }

    public static String isBan(String account) {
        String sql = "select state from users where account = '" + account + "'";
        List<String> list;
        try {
            list = JDBCUtils.executeSelect(sql, "state");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!list.isEmpty()) {
            if (list.get(0).equals("1")){
                return "success";
            }
        }
        return "fail";
    }

    public static String getAllUsers(){
        String sql = "select * from users";
        List<String> list;
        List<String> jsonList = new ArrayList<>();
        try {
            list = JDBCUtils.executeSelect(sql, "id", "account", "password", "name", "avatar", "balance", "orders", "state", "insert_time", "update_time");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        int i = 0;
        while(true) {
            // 检查是否超出范围
            if (10 * i + 9 >= list.size()) {
                break; // 如果超出范围，跳出循环
            }
            String decryptedPassword;
            try {
                SecretKey key = AESUtils.loadKey();
                decryptedPassword = AESUtils.decrypt(list.get(10 * i + 2), key);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            User user = new User(
                    Integer.parseInt(list.get(10 * i)),
                    list.get(10 * i + 1),
                    decryptedPassword,
                    list.get(10 * i + 3),
                    list.get(10 * i + 4),
                    Double.parseDouble(list.get(10 * i + 5)),
                    Integer.parseInt(list.get(10 * i + 6)),
                    Integer.parseInt(list.get(10 * i + 7)),
                    list.get(10 * i + 8),
                    list.get(10 * i + 9)
            );
            i++;
            JSONObject jsonObject = (JSONObject) JSON.toJSON(user);
            jsonObject.put("name", User.getName());
            String jsonString = jsonObject.toJSONString();
            jsonList.add(jsonString);
        }
        return JSON.toJSONString(jsonList);
    }

    public static String deleteUser(String id) {
        String sql = "delete from users where id = ?";
        int num;
        try {
            num = JDBCUtils.executeUpdate(sql, id);
        } catch (Exception e){
        throw new RuntimeException(e);
        }
        if (num >= 1){
            return "success";
        } else {
            return "fail";
        }
    }
}
